import traceback

from fastapi import APIRouter
from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.core.requests_core import MsgCode

from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo, SUCCESS
from apps.crawler_platform.core_api.models import SaveMongoModel
from apps.crawler_platform.core_platform.g_model import InputPlatformModel
from apps.crawler_platform.util.nosqlhelper import NOSQLHelper
from apps.crawler_platform.util.requestapihelper import RequestApiHelper
from apps.sql_app.mmongodb import Coll

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/taskinfo/params_post_date")
async def exec_sql(inputs: InputPlatformModel[str]):
    pass



@router.post("/taskinfo/test_sdb")
async def tt(inputs: InputPlatformModel[SaveMongoModel]):
    return_info = ReturnInfo()
    table = inputs.data.table
    data = inputs.data.data
    _id = data.get("_id")
    if not _id:
        _id = data["lngid"]
        data["_id"] = _id
    mongo_conn = Coll.get_table_conn(table)  # 根据table名取得mongo链接
    try:
        result = await NOSQLHelper.insert_one(mongo_conn, data)
    except:
        traceback.print_exc()
    return_info.status = SUCCESS
    return_info.msg_code = MsgCode.SUCCESS_CODE
    return_info.msg = "保存到mongodb成功"
    return_info.data = ""
    return return_info.todict()


@router.post("/taskinfo/test_sdb_rest")
async def tt():
    return_info = ReturnInfo()
    rrq = RequestApiHelper.get_rrq()
    header = {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "Accept": "application/json",
        "Host": "192.168.31.24:11810"
    }
    form = {
        "cmd": "query",
        "name": "html_other.other",
        "returnnum": 1
        # "filter": {"_id": "policy_guoce_detail_157570"}
    }
    kwargs = {
        "rrq": rrq,
        "header": header,
        "url": "http://192.168.31.24:11810",
        "timeout": 30,
        "data": form,
        "moths": MRequest.POST,
        "middler_list": [rrq.status_code_middlerwares]
    }
    bools, msg_dicts = await RequestApiHelper.etl_remote_meta(**kwargs)
    return_info.status = SUCCESS
    return_info.msg_code = MsgCode.SUCCESS_CODE
    return_info.msg = "保存到mongodb成功"
    return_info.data = ""
    return return_info.todict()
